/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _DAL_FASTDDS_GUID_COUNT_MAP_HPP_
#define _DAL_FASTDDS_GUID_COUNT_MAP_HPP_

#include <mutex>
#include <map>
#include <fastdds/rtps/common/Guid.h>

using namespace eprosima::fastrtps::rtps;

namespace dal_fastdds {

class GuidCountMap
{
public:
    void Update(const GUID_t& key, uint32_t cnt) {
        std::lock_guard<std::mutex> lock(guid_cnt_map_mutex_);
        guid_cnt_map_[key] = cnt;
    }

    void AddOrIncrease(const GUID_t& key) {
        std::lock_guard<std::mutex> lock(guid_cnt_map_mutex_);
        auto it = guid_cnt_map_.find(key);
        if (it != guid_cnt_map_.end()) {
            guid_cnt_map_[key] = guid_cnt_map_[key] + 1;
        } else {
            guid_cnt_map_[key] = 1;
        }
    }

    void Decrease(const GUID_t& key) {
        std::lock_guard<std::mutex> lock(guid_cnt_map_mutex_);
        auto it = guid_cnt_map_.find(key);
        if (it != guid_cnt_map_.end()) {
            guid_cnt_map_[key] = guid_cnt_map_[key] - 1;
        }
    }

    uint32_t Get(const GUID_t& key) {
        std::lock_guard<std::mutex> lock(guid_cnt_map_mutex_);
        auto it = guid_cnt_map_.find(key);
        if (it != guid_cnt_map_.end()) {
            return it->second;
        }
        return 0;
    }

private:
    std::map<GUID_t, uint32_t> guid_cnt_map_;
    std::mutex guid_cnt_map_mutex_;
};

}  // namespace dal_fastdds

#endif  // _DAL_FASTDDS_GUID_COUNT_MAP_HPP_